﻿using System.Collections.Concurrent;
using System.Net.Sockets;
using System.Text;

namespace EasyNet.TCP.Server
{
    public class Client : IClient
    {
        //非后备字段
        private readonly object[] lockers = new object[3];//线程锁
        //后备字段
        internal ConcurrentQueue<FileMsg> _sendingFiles = new ConcurrentQueue<FileMsg>();
        internal ConcurrentQueue<FileMsg> _receivingFiles = new ConcurrentQueue<FileMsg>();
        private string _id;
        private string _directory;
        private Encoding _encoding = Encoding.UTF8;

        public string ID 
        {
            get 
            {
                return _id;
            }
            set 
            {
                lock (lockers[0]) 
                {
                    _id = value;
                }
            } 
        }
        public string Directory
        {
            get
            {
                return _directory;
            }
            set
            {
                lock (lockers[1])
                {
                    _directory = value;
                }
            }
        }
        public Encoding Encoding
        {
            get
            {
                return _encoding;
            }
            set
            {
                lock (lockers[2])
                {
                    _encoding = value;
                }
            }
        }
        public bool Connected
        {
            get
            {
                return TCPTools.SocketConnected(ClientSocket);
            }
        }
        public IReadOnlyCollection<FileMsg> SendingFiles
        {
            get
            {
                return _sendingFiles;
            }
        }
        public IReadOnlyCollection<FileMsg> ReceivingFiles
        {
            get
            {
                return _receivingFiles;
            }
        }
        public string IP { get; private set; }
        public int Port { get; private set; }
        internal Socket ClientSocket { get; private set; }
        internal Client(Socket client_socket)
        {
            for (int i = 0; i < lockers.Length; i++)
            {
                lockers[i] = new object();
            }
            ClientSocket = client_socket;
            IP = client_socket.LocalEndPoint.ToString().Split(':')[0];
            Port = Convert.ToInt32(client_socket.LocalEndPoint.ToString().Split(':')[1]);
        }
    }
}
